import { Device } from "@/api/interface/iot";
import { getSiteList, modSite } from "@/api/modules/iot/site";
import notData from "@public/images/decoration/O1CN01pgFgsH1CNe7RZJtSW_!!6000000000069-0-tps-696-560.jpg";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import { MessageType } from "@/enums/messageEnum";
import { ProductStatusEnum } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { filePrefix } from "@/hooks/useSystem";
import { PublicStore } from "@/stores/modules/public";
import { uploadImg } from "@/api/modules/upload";
import UploadImg from "@/components/Upload/Img.vue";
import { dataFormat } from "@/utils/format";
import { openWin } from "@/utils/routerUtil";
import { showMsg, showTips } from "@/utils/util";
import { ElForm } from "element-plus";
import { useI18n } from "vue-i18n";
import "./site.scss";
import { SYSTEM_ID } from "@/config/config";
export default defineComponent({
	name: "ProductList",
	setup() {
		const { t } = useI18n();
		const publicStore = PublicStore();
		const collapsedSearch = ref<boolean>(false);
		const initParam = reactive<Device.ReqProduct>({ pageIndex: 1, pageSize: 9 });
		const selected = ref<any[]>([]);
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			useAuthButtons().then(btnList => {
				console.log(btnList);
				buttonsList.value = btnList.filter((item: any) => !item.btnGroup || item.btnGroup != 3);
			});
		});
		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			// return {
			// 	result: {
			// 		records: [{ id: "root-BgcIAQIDBAUGBwgJKVRWGT", name: "111", description: "描述描述描述描述描述描述描述描述描述描述" }]
			// 	}
			// };
			return getSiteList(params);
		};
		onActivated(() => {
			proTable.value.getTableList();
		});
		const detailDialog = reactive<any>({
			title: t("product.dialog_title.add"),
			detail: {},
			visible: false
		});
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			name: [{ required: true, message: "现场名称不能为空", trigger: "change" }]
		});
		const clickBtn = async (fn: string, row: any) => {
			let rows: any[] = row?.selectList || [row];
			selected.value = rows;
			switch (fn) {
				case "sync":
					if (rows.length != 1) {
						showMsg(t("select.record.one"), MessageType.warning);
						return;
					}
					syncDialog.configChecked = ["dept", "file", "site", "alarm", "device", "sensor", "product"];
					syncDialog.detail = { ...rows[0] };
					syncDialog.detail.name = syncDialog.detail.name || syncDialog.detail.deptName;
					syncDialog.visible = true;
					break;
				case "detail":
					if (rows.length != 1) {
						showMsg(t("select.record.one"), MessageType.warning);
						return;
					}
					let page;
					if (import.meta.env.DEV) {
						page = `http://127.0.0.1:8080/#/login?deptId=${rows[0].deptId}&token=${publicStore.token}`;
					} else {
						page = location.origin + `/aicube/#/login?deptId=${rows[0].deptId}&token=${publicStore.token}`;
					}
					openWin(page);
					break;
				case "mod":
					if (rows.length != 1) {
						showMsg(t("select.record.one"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...rows[0] };
					detailDialog.detail.name = detailDialog.detail.name || detailDialog.detail.deptName;
					detailDialog.visible = true;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			// { prop: "model", label: t("product.tablist_label.model"), search: { el: "input" } },
			{ prop: "name", label: "现场名称", search: { el: "input" } },
			// { prop: "status", label: "产品状态", search: { slot: {} } },
			// { prop: "deviceType", label: t("product.tablist_label.device_type"), search: { slot: {} } },
			{ prop: "description", label: "现场描述" },
			{ prop: "createTime", label: t("product.tablist_label.create_time") },
			{ prop: "operation", label: t("product.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDetail = async () => {
			let valid = await formRef.value?.validate();
			if (!valid) {
				return;
			}
			detailDialog.detail = { ...detailDialog.detail, ...syncDialog.detail };
			detailDialog.detail.config = {};
			syncDialog.configChecked.forEach(type => {
				detailDialog.detail.config[type] = true;
			});
			modSite(detailDialog.detail).then(res => {
				let ok = showTips(res.code, "修改现场", res.message);
				if (ok) {
					detailDialog.visible = false;
					proTable.value.getTableList();
				}
			});
		};

		const syncDialog = reactive({
			title: "同步现场数据到云",
			detail: {} as any,
			configChecked: [] as string[],
			configList: [
				{ label: "分组信息", key: "dept" },
				{ label: "现场信息", key: "site" },
				{ label: "产品模型", key: "product" },
				{ label: "设备信息", key: "device" },
				{ label: "历史数据", key: "sensor" },
				{ label: "告警记录", key: "alarm" },
				{ label: "文件信息", key: "file" }
			],
			visible: false
		});
		return () => {
			return (
				<div>
					<DialogBox title="编辑" width="750px" v-model:visible={detailDialog.visible} onConfirm={submitDetail}>
						<div class="flex">
							<div class="w-52 pr-4">
								<UploadImg
									v-model:imageUrl={detailDialog.detail.photo}
									emptyTips="现场照片"
									width="100%"
									height="250px"
									api={uploadImg}
									headers={{
										Authentication: publicStore.token,
										systemid: SYSTEM_ID,
										timestamp: Date.now()
									}}
								></UploadImg>
							</div>
							<div class="flex-1">
								<el-form model={detailDialog.detail} ref={formRef} rules={formRule} label-width="100px">
									<el-form-item label="现场名称" prop="name">
										<el-input v-model={detailDialog.detail.name} />
									</el-form-item>
									<el-form-item label="现场描述" prop="description">
										<el-input v-model={detailDialog.detail.description} type="textarea" rows={8} />
									</el-form-item>
								</el-form>
							</div>
						</div>
					</DialogBox>
					<DialogBox title="同步数据" width="600px" v-model:visible={syncDialog.visible} onConfirm={submitDetail}>
						<el-alert type="error">
							{{
								title: () => {
									return <div class="font-bold text-red-500">警告</div>;
								},
								default: () => {
									return (
										<div class="text-red-500">
											<div>当前操作会将现场数据同步到云端。</div>
											<div>执行同步操作后，将会以现场数据为标本，覆盖并重置云端现有数据，请谨慎操作！</div>
										</div>
									);
								}
							}}
						</el-alert>

						<el-form class="mt-4" model={syncDialog.detail} ref={formRef} rules={formRule} label-width="100px">
							<el-form-item label="现场名称" prop="name">
								<el-input v-model={syncDialog.detail.name} />
							</el-form-item>
							<el-form-item label="同步数据" prop="configList">
								<el-checkbox-group v-model={syncDialog.configChecked}>
									{syncDialog.configList.map(conf => {
										return <el-checkbox label={conf.key}>{conf.label}</el-checkbox>;
									})}
								</el-checkbox-group>
							</el-form-item>
						</el-form>
					</DialogBox>
					{collapsedSearch.value ? null : (
						<BaseSearchForm class="mb-2">
							<el-form
								class="flex pt-4 pl-4 pr-4 bg-white"
								style="flex-wrap: wrap;"
								onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? proTable.value.getTableList() : null)}
							>
								<el-form-item class="search-item" label="现场名称">
									<el-input v-model={initParam.name} placeholder="现场名称" />
								</el-form-item>
								<el-form-item class="search-item">
									<el-button type="primary" class="iconfont iconsearch" onClick={() => proTable.value.getTableList()}>
										{t("common.btn.search")}
									</el-button>
								</el-form-item>
							</el-form>
						</BaseSearchForm>
					)}
					<ProTable
						ref={proTable}
						custSearch
						onSearchCollapsed={val => {
							collapsedSearch.value = val;
						}}
						ignoreInit
						title={buttonsList.value.length ? "" : "现场管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={8}
						onSelected={val => (selected.value = val)}
					>
						{{
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button
											onClick={() => clickBtn(item.path, scope)}
											type={item.btnClass}
											disabled={selected.value.length ? false : true}
										>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							cardBody: (scope: any) => {
								return (
									<div class="product-card">
										<div class="bg w-full h-full absolute z-0">
											<el-image
												fit="fill"
												class="w-full h-full"
												src={scope.row.photo ? `${filePrefix()}${scope.row.photo}` : notData}
											/>
										</div>
										<div class="absolute z-10 w-full h-full card-container">
											<div class="master-row flex items-center pt-8 pl-8 pr-8">
												<div class="product-name flex-1 overflow">
													<div class="text-lg font-bold">{scope.row.name || scope.row.deptName}</div>
													<div class="time text text-sm text-gray-500 ">{dataFormat("datetime", scope.row.lastLiveTime)}</div>
												</div>
												{buttonsList.value.find((item: any) => item.path == "del" || item.path == "mod") ? (
													<div style="margin-top: -25px;">
														<el-dropdown
															v-slots={{
																dropdown: () => {
																	return (
																		<el-dropdown-menu>
																			{buttonsList.value.find((item: any) => item.path == "mod") ? (
																				<el-dropdown-item onClick={() => clickBtn("mod", scope.row)}>
																					{t("product_card.dropdpwn_btn.edit")}
																				</el-dropdown-item>
																			) : null}
																			{buttonsList.value.find((item: any) => item.path == "del") ? (
																				<el-dropdown-item onClick={() => clickBtn("del", scope.row)}>
																					{t("product_card.dropdpwn_btn.delete")}
																				</el-dropdown-item>
																			) : null}
																		</el-dropdown-menu>
																	);
																}
															}}
														>
															<el-link underline={false}>
																<i class="iconfont iconmore-vertical" style="font-size:22px" />
															</el-link>
														</el-dropdown>
													</div>
												) : null}
											</div>
											<div class="h-24 flex items-center pl-8 pr-8 text-gray-500">
												<div class="text">{scope.row.description || scope.row?.server?.net?.wan || "--"}</div>
											</div>
											<div class="flex pt-6 pl-8 pr-8 ">
												<el-button type="primary" onClick={() => clickBtn("detail", scope.row)}>
													{t("product_card.btn.detail")}
													<i class="iconfont iconbx-right-arrow-alt ml-1"></i>
												</el-button>
											</div>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										onlineLabel={ProductStatusEnum.DEPLOY_LABEL}
										offlineLabel={ProductStatusEnum.DEVELOP_LABEL}
									/>
								);
							},
							name: (scope: any) => {
								return scope.row.nane || scope.row.deptName;
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										{buttonsList.value.map((item: any) => {
											<el-link type="danger" onClick={() => clickBtn(item.path, scope.row)}>
												{item.menuName}
											</el-link>;
										})}
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle={t("product.empty.subtitle")}
											btnText={t("product.empty.btntext")}
											showButton={buttonsList.value.some((item: any) => item.path == "add")}
											onAdd={() => {
												clickBtn("add", {});
											}}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
